﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

namespace LocalSend2 {

	/// <summary>
	/// 终端
	/// </summary>
	internal class Client {

		/// <summary>
		/// 终端IP
		/// </summary>
		public string Ip;

		/// <summary>
		/// 终端接收数据的端口（TCP）
		/// </summary>
		public int Port;

		/// <summary>
		/// 别名
		/// </summary>
		public string NickName;

		/// <summary>
		/// 最后存活时间，以接收到ID报告时间为准
		/// </summary>
		public DateTime LastAliveTime;

		/// <summary>
		/// 显示名字
		/// </summary>
		public string DisplayName => NickName + "(" + Ip + ")";

		/// <summary>
		/// 获取该终端机上的文件列表
		/// </summary>
		/// <returns>文件列表</returns>
		public List<ShareFile> GetFileList() {
			List<ShareFile> fileList = new List<ShareFile>();

			// 验证机器连接
			TcpClient tcp = new TcpClient(Ip, Port);
			if (!tcp.Connected) {
				throw new Exception("终端连接失败，" + Ip + ":" + Port);
			}
			NetworkStream netStream = tcp.GetStream();
			byte[] bytes = Encoding.Default.GetBytes("GET_FILE_LIST");
			netStream.Write(bytes, 0, bytes.Length);

			bytes = new byte[102400]; // 就100k，文件列表长了就不行了
			int len = netStream.Read(bytes, 0, 102400);

			string recvStr = Encoding.Default.GetString(bytes, 0, len);
			if (recvStr == "NO_FILE") return fileList;

			// 解析文件信息，ID|Length|Name`...
			foreach (string item in recvStr.Split('`')) {
				string[] sl = item.Split('|');
				if (sl.Length != 3) continue;
				fileList.Add(new ShareFile {
					ID = int.Parse(sl[0]),
					Length = long.Parse(sl[1]),
					Name = sl[2]
				});
			}
			return fileList;
		}
	}
}
